/*
 * NotificationClickReceiver.java
 * business
 *
 * Created by ChenTao on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.yidiandao.business.constant.Intents;
import com.yidiandao.business.data.push.PushProcessManager;
import com.yidiandao.business.ui.splash.SplashActivity;
import com.yidiandao.business.utils.ActivityStack;
import com.yidiandao.business.utils.PushUtils;
import com.yidiandao.business.utils.UIUtils;

/**
 * Notification 点击事件处理的Receiver
 */
public class NotificationClickReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // 点击Notification
        String pushType = intent.getStringExtra(Intents.EXTRA_PUSH_TYPE);

        PushProcessManager manager = new PushProcessManager(context, null, false);
        manager.setPushProcess(pushType);
        // 清除未读标识
//        manager.clearUnRedPushMessageRedPoint();

        Intent newActivityIntent = manager.getOpenNotificationJumpActivityIntent();
        if (newActivityIntent != null) {
            // 将推送的数据传送到新页面中
            newActivityIntent.putExtras(intent);
        }

        // 判断App进程是否存活,通过ActivityTask判断
        // context 没有ActivityTask
        if (ActivityStack.getActivityStack().size() != 0 && newActivityIntent != null) {
            newActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(newActivityIntent);
        } else {
            Intent launchIntent = new Intent(context, SplashActivity.class);
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            if (newActivityIntent == null) {
                // 当前推送的type 为 Null ---> 点击Notification 会让其跳转到Splash页面，因此不需要重复跳转
                context.startActivity(launchIntent);
            } else {
                context.startActivities(new Intent[]{launchIntent, newActivityIntent});
            }
        }

        // 统计推送通知被打开
        PushUtils.reportNotificationOpened(
                UIUtils.getContext(), intent.getStringExtra(Intents.EXTRA_MESSAGE_ID));
    }
}
